package com.gemme.gemme.shequ;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.gemme.gemme.R;
import com.gemme.gemme.fragment.BaseLazyFragment;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.GlideCircleTransform;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.ninegridview.ImageInfo;
import com.gemme.gemme.ninegridview.NineGridView;
import com.gemme.gemme.ninegridview.NineGridViewClickAdapter;
import com.gemme.gemme.ninegridview.NineGridViewLoader;
import com.gemme.gemme.util.MobileUtil;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.GuanzhuHeadView;
import com.gemme.gemme.view.GuanzhuSingleItemView;
import com.gemme.gemme.view.RefreshView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by sp on 2019/7/18.
 * 首页
 */
public class Guanzhu2Fragment extends BaseLazyFragment {

    View inflate;
    Context mContext;
    RefreshView refreshView;
    GuanzhuHeadView guanzhuHeadView;
    GuanZhu2Adapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        inflate = inflater.inflate(R.layout.fragment_guanzhu2, container, false);

        mContext = Guanzhu2Fragment.this.getContext();

        initView(inflate);

        return inflate;
    }

    private void initView(View inflate) {
        refreshView = inflate.findViewById(R.id.refreshView);
        guanzhuHeadView = new GuanzhuHeadView(mContext);
        refreshView.addHeaderView(guanzhuHeadView);
        refreshView.setLayoutManager(new LinearLayoutManager(mContext));
        refreshView.canRefresh(true);
        refreshView.setGMOnFreshListener(new RefreshView.GMOnFreshListener() {
            @Override
            public void onRefresh() {
                onLazyLoad();
                System.out.println("");
            }

            @Override
            public void onLoadMore() {
                System.out.println("");
            }
        });
    }

    @Override
    public void onLazyLoad() {
        getDataGUanzhu();
        getDataTuijian();
    }

    private void getDataTuijian() {
        try {
            //先用固定值
            String url = DataManager.BaseUrl + "community/appccontent/recommend";

            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));

            DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    System.out.println("");
                    try {
                        SheQUTuijianBean sheQUTuijianBean = JSON.parseObject(response, SheQUTuijianBean.class);
                        List<SheQUTuijianBean.DataBean> data = sheQUTuijianBean.getData();
                        guanzhuHeadView.setData(sheQUTuijianBean);
                    } catch (Exception e) {

                    }
                }
            });
        } catch (Exception e) {
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getDataGUanzhu();
    }

    private void getDataGUanzhu() {
        try {
            String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
            String url = DataManager.BaseUrl + "community/appccontent/follow?userId=" + userId;

            /**
             * 去除tokenjjm
             */
            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try {
                        List<CommunityBean.DataBean> data = JSON.parseArray((new JSONObject(response)).getJSONObject("data").getString("records"), CommunityBean.DataBean.class);
                        if (data == null)
                            return;
                        System.out.println();


                        if (adapter == null) {
                            adapter = new GuanZhu2Adapter(data);
                            refreshView.setAdapter(adapter);
                        } else {
                            adapter.setData(data);
                            adapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {

                    }
                    System.out.println("");
                }
            });
        } catch (Exception e) {
        }
    }

    public class GuanZhu2Adapter extends RecyclerView.Adapter<GuanZhu2Adapter.ViewHolder> {

        private List<CommunityBean.DataBean> adapterList;

        public GuanZhu2Adapter(List<CommunityBean.DataBean> adapterList) {
            this.adapterList = adapterList;
        }

        public void setData(List<CommunityBean.DataBean> adapterList) {
            this.adapterList = adapterList;
        }

        @NonNull
        @Override
        public GuanZhu2Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.item_guanzhu2_9, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new GuanZhu2Adapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull GuanZhu2Adapter.ViewHolder holder, int position) {
            try {
                CommunityBean.DataBean dataBean = adapterList.get(position);
                String type = dataBean.getType();
                if ("1".equals(type)) { //图片
                    holder.singleitem.setVisibility(View.GONE);
                    holder.mutiitem.setVisibility(View.VISIBLE);

                    String picturePath = dataBean.getPicturePath();
                    String[] picArr = picturePath.split(",");

                    List<String> imglist = new ArrayList<>();
                    if (picArr.length > 0) {
                        for (int i = 0; i < picArr.length; i++) {
                            imglist.add(picArr[i]);
                        }
                    }

                    ArrayList<ImageInfo> imageInfo = new ArrayList<>();

                    for (int i = 0; i < imglist.size(); i++) {
                        String image = imglist.get(i);
                        ImageInfo info = new ImageInfo();
                        info.setThumbnailUrl(image);
                        info.setBigImageUrl(image);
                        imageInfo.add(info);
                    }

                    holder.mutiitem.setImageLoader(new NineGridViewLoader());
                    NineGridViewClickAdapter nineAdapter = new NineGridViewClickAdapter(getActivity(), imageInfo);
                    holder.mutiitem.setAdapter(nineAdapter);
                    nineAdapter.setItemClick(new NineGridViewClickAdapter.ItemClick() {
                        @Override
                        public void itemClick(int index) {
                            Intent intent = new Intent(mContext, ShequDetailActivity.class);
                            intent.putExtra("data", dataBean.getId());
                            startActivity(intent);
                        }
                    });

                } else {//视屏
                    holder.singleitem.setVisibility(View.VISIBLE);
                    holder.mutiitem.setVisibility(View.GONE);
                    holder.singleitem.setData(dataBean);
                }

                String headImageUrl = StrUtil.noNUll(dataBean.getHeadImg());
                if (!TextUtils.isEmpty(headImageUrl))
                    Glide.with(mContext).load(headImageUrl)
                            .transform(new GlideCircleTransform(mContext))
                            .into(holder.iv_head);
                String nickName = StrUtil.noNUll(dataBean.getNickName());
                holder.tv_name.setText(TextUtils.isEmpty(nickName) ? MobileUtil.hideMiddleMobile(dataBean.getUserMobile()) : nickName);
                holder.tv_content.setText(StrUtil.noNUll(dataBean.getCdescribe()));
                holder.tv_time.setText(dataBean.getCreateTime().substring(5));
                if (dataBean.getIsLike() == 1) {
                    holder.iv_link.setBackgroundResource(R.drawable.pc_dianzan_select);
                } else {
                    holder.iv_link.setBackgroundResource(R.drawable.pc_dianzan_shequ);
                }
                holder.tv_link.setText(StrUtil.toINt(dataBean.getLikeCounts()) + "");
                holder.tv_pinglun.setText(StrUtil.toINt(dataBean.getCommentsCounts()) + "");
//                tv_share
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(mContext, ShequDetailActivity.class);
                        intent.putExtra("data", dataBean.getId());
                        startActivity(intent);
                    }
                });

                holder.ll_link.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (dataBean.getIsLike() == 1) {
                            cancelUserLike(dataBean);
                        } else {
                            dianzan(dataBean);
                        }
                    }
                });
            } catch (Exception e) {

            }
        }

        private void dianzan(CommunityBean.DataBean dataBean) {
            try {

                String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
                String type = "1";
                String contentId = dataBean.getId() + "";
                int likeUserId = dataBean.getUserId();
/*
            String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                    "userId=" + userId +
                    "&type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";
*/

                String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                        "type=" + type +
                        "&contentId=" + contentId +
                        "&likeUserId=" + likeUserId +
                        "";


                HashMap<String, String> headMap = new HashMap<>();
                headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
                DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("");

                        try {
                            if (DataPares.isSucess(mContext, response)) {
                                Toast.makeText(mContext, "点赞成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "点赞失败", Toast.LENGTH_SHORT).show();
                            }
                            getDataGUanzhu();
                        } catch (Exception e) {

                        }
                    }
                });
            } catch (Exception e) {

            }

        }

        private void cancelUserLike(CommunityBean.DataBean dataBean) { //
            try {

                String contentId = dataBean.getId() + "";
                int likeUserId = dataBean.getUserId();

//            47.114.162.17:9999/community/appcuserslike/cancelUserLike?type=2&likeUserId=152&contentId=47

                String url = DataManager.BaseUrl + "community/appcuserslike/cancelUserLike?" +
                        "type=" + "1" +
                        "&contentId=" + contentId +
                        "&likeUserId=" + likeUserId +
                        "";


                HashMap<String, String> headMap = new HashMap<>();
                headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
                DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("");

                        try {
                            if (DataPares.isSucess(mContext, response)) {
                                Toast.makeText(mContext, "取消成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "取消失败", Toast.LENGTH_SHORT).show();
                            }
                            getDataGUanzhu();
                        } catch (Exception e) {

                        }
                    }
                });
            } catch (Exception e) {

            }

        }


        @Override
        public int getItemCount() {
            return adapterList.size();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            GuanzhuSingleItemView singleitem;
            NineGridView mutiitem;
            ImageView iv_head;
            TextView tv_name;
            TextView tv_time;

            TextView tv_link;
            ImageView iv_link;
            TextView tv_pinglun;
            TextView tv_share;
            TextView tv_content;
            LinearLayout ll_link;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                singleitem = itemView.findViewById(R.id.singleitem);

                mutiitem = itemView.findViewById(R.id.mutiitem);

                iv_head = itemView.findViewById(R.id.iv_head);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_time = itemView.findViewById(R.id.tv_time);

                tv_link = itemView.findViewById(R.id.tv_link);
                iv_link = itemView.findViewById(R.id.iv_link);
                tv_pinglun = itemView.findViewById(R.id.tv_pinglun);
                tv_share = itemView.findViewById(R.id.tv_share);
                tv_content = itemView.findViewById(R.id.tv_content);
                ll_link = itemView.findViewById(R.id.ll_link);
            }
        }
    }

}
